import time, os
from PIL import Image
from pyquery import PyQuery as pq
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.action_chains import ActionChains

from cjy.chaojiying import Chaojiying_Client as cjy


_path = os.path.dirname(__file__)


class QPLogin(cjy):

    login_uername = 'htg_nice'
    login_password = 'htg3120400125'

    def __init__(self, url):
        self.url = url
        self.driver = webdriver.Chrome()

    def open_url(self, url):
        # 打开链接
        self.driver.get(url)

    def location_element(self, by, path, driver=None):
        if not driver:
            driver = self.driver
        return driver.find_element(by, path)

    def location_elements(self, by, path, driver=None):
        if not driver:
            driver = self.driver
        return driver.find_elements(by, path)

    def wait_element(self, by, path, driver=None):
        # 隐性等待
        if not driver:
            driver = self.driver
        element = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((by, path)))
        return element

    def get_time(self):
        timestrmap = time.strftime('%Y%m%d_%H.%M.%S')
        return timestrmap

    def capture_img(self, imgPath, element):
        """
        :param imgPath: 全图的路径
        :param element: 截取验证码元素
        :return:
        """

        left = element.location['x']    # 元素的x坐标
        top = element.location['y']     # 元素的y坐标
        elementWidth = left + element.size['width']     # 元素的宽
        elementHeight = top + element.size['height']    # 元素的高

        picture = Image.open(imgPath)  #
        yzm_picture = picture.crop((left, top, elementWidth, elementHeight))  # 截取想要图片元素
        timestrmap = time.strftime('%Y%m%d_%H.%M.%S')
        yzm_imgPath = os.path.join(_path, '{}/login_picture/yz_{}.png'.format(_path, timestrmap))
        yzm_picture.save(yzm_imgPath)
        return yzm_imgPath

    def click_yzm(self, cjy_result_dict):
        # {'err_no': 0, 'err_str': 'OK', 'pic_id': '2088122413328500007', 'pic_str': '188,147|248,81', 'md5': '80b6c0d0354da4169d8c281d36a7fc55'}
        pic_str_list = cjy_result_dict.get('pic_str').split('|')
        coords = [[int(number) for number in coord.split(',')] for coord in pic_str_list]  # 坐标 [[],[],[]..]
        print(coords)

        for coord in coords:  # 根据列表点击验证码
            time.sleep(2)
            yzm_img_element = self.location_element(by=By.ID, path='J-loginImg')
            ActionChains(self.driver).move_to_element_with_offset(to_element=yzm_img_element, xoffset=coord[0], yoffset=coord[1]).click().perform()

    def input_login_info(self):
        username_element = self.location_element(by=By.ID, path='J-userName')
        password_element = self.location_element(by=By.ID, path='J-password')

        username_element.send_keys(self.login_uername)
        time.sleep(1)
        password_element.send_keys(self.login_password)

    def click_login_button(self):
        login_button = self.location_element(by=By.ID, path='J-login')
        login_button.click()

    def qplogin(self):
        self.driver.maximize_window()
        time.sleep(1)
        self.open_url(url=self.url)

        zh_login_button = self.wait_element(by=By.CSS_SELECTOR, path='.login-hd-account a')  # 账号登录按钮
        ewm_login_button = self.wait_element(by=By.CSS_SELECTOR, path='.login-hd-code a')  # 二维码登录按钮
        time.sleep(1)
        zh_login_button.click()

        time.sleep(1)
        timestrmap = self.get_time()
        img_path = os.path.join(_path, 'login_picture/jt_{}.png'.format(timestrmap))
        self.driver.save_screenshot(img_path)  # 截屏，整个屏幕
        yzm_element = self.location_element(driver=self.driver, by=By.ID, path='J-loginImg')

        time.sleep(1)
        yzm_imgPath = self.capture_img(imgPath=img_path, element=yzm_element)  # 截取验证码图片

        cjy_result_dict = self.cjy_run(img_path=yzm_imgPath)

        # print(cjy_result_dict)
        self.click_yzm(cjy_result_dict=cjy_result_dict)

        self.input_login_info()

        self.click_login_button()

        cookies = self.driver.get_cookies()

        return cookies


if __name__ == '__main__':
    qp = QPLogin(url='https://kyfw.12306.cn/otn/resources/login.html')
    qp.qplogin()
